package com.xunyin.modules.couponnew.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xunyin.api.XunyinException;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.config.Message;
import com.xunyin.constant.Constants;
import com.xunyin.enums.CouponTypeEnum;
import com.xunyin.enums.SendWayEnum;
import com.xunyin.enums.UserCouponStatusEnum;
import com.xunyin.modules.couponnew.domain.MtCoupon;
import com.xunyin.modules.couponnew.domain.MtUserCoupon;
import com.xunyin.modules.couponnew.dto.ConponStatDto;
import com.xunyin.modules.couponnew.param.CouponReceiveParam;
import com.xunyin.modules.couponnew.service.CouponService;
import com.xunyin.modules.couponnew.service.UserCouponService;
import com.xunyin.modules.couponnew.service.dto.CouponDto;
import com.xunyin.modules.couponnew.service.dto.MtUserCouponQueryCriteria;
import com.xunyin.modules.couponnew.service.dto.MyCouponDto;
import com.xunyin.modules.couponnew.service.mapper.MtUserCouponMapper;
import com.xunyin.modules.mtstore.service.StoreService;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.modules.user.service.YxUserService;
import com.xunyin.modules.user.service.dto.WechatUserDto;
import com.xunyin.modules.user.service.mapper.UserMapper;
import com.xunyin.pagination.PaginationRequest;
import com.xunyin.pagination.PaginationResponse;
import com.xunyin.utils.DateUtil;
import com.xunyin.utils.SeqUtil;
import com.xunyin.utils.StringUtil;
import com.xunyin.utils.StringUtils;
import com.xunyin.web.ResponseObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 会员卡券业务实现类
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Service
@RequiredArgsConstructor
@Slf4j
//@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserCouponServiceImpl extends BaseServiceImpl<MtUserCouponMapper, MtUserCoupon> implements UserCouponService {

    @Autowired
    private MtUserCouponMapper mtUserCouponMapper;

    @Autowired
    private CouponService couponService;

    @Autowired
    private YxUserService userService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private UserMapper yxUserMapper;

    /**
     * 分页查询券列表
     *
     * @param paginationRequest
     * @return
     */
    @Override
    public PaginationResponse<MtUserCoupon> queryUserCouponListByPagination(PaginationRequest paginationRequest) {
        com.github.pagehelper.Page<MtUserCoupon> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        LambdaQueryWrapper<MtUserCoupon> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ne(MtUserCoupon::getStatus, "D");

        String status = paginationRequest.getSearchParams().get("status") == null ? "" : paginationRequest.getSearchParams().get("status").toString();
        if (StringUtils.isNotBlank(status)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getStatus, status);
        }
        String type = paginationRequest.getSearchParams().get("type") == null ? "" : paginationRequest.getSearchParams().get("type").toString();
        if (StringUtils.isNotBlank(type)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getType, type);
        }
/*        String couponId = paginationRequest.getSearchParams().get("couponId") == null ? "" : paginationRequest.getSearchParams().get("couponId").toString();
        if (StringUtils.isNotBlank(couponId)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getCouponId, couponId);
        }
        String code = paginationRequest.getSearchParams().get("code") == null ? "" : paginationRequest.getSearchParams().get("code").toString();
        if (StringUtils.isNotBlank(code)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getCode, code);
        }*/
        String mobile = paginationRequest.getSearchParams().get("mobile") == null ? "" : paginationRequest.getSearchParams().get("mobile").toString();
        if (StringUtils.isNotBlank(mobile)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getMobile, mobile);
        }

        String storeId = paginationRequest.getSearchParams().get("storeId") == null ? "" : paginationRequest.getSearchParams().get("storeId").toString();
        if (StringUtils.isNotBlank(storeId)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getStoreId, storeId);
        }
        String storeIdList = paginationRequest.getSearchParams().get("storeIdList") == null ? "" : paginationRequest.getSearchParams().get("storeIdList").toString();
        if (StringUtils.isNotBlank(storeIdList)) {
            lambdaQueryWrapper.in(MtUserCoupon::getStoreId, JSONArray.parseArray(storeIdList, Integer.class));
        }

        lambdaQueryWrapper.orderByDesc(MtUserCoupon::getId);
        List<MtUserCoupon> dataList = mtUserCouponMapper.selectList(lambdaQueryWrapper);
/*        for(int i=0;i<dataList.size();i++){
            MtUserCoupon mtUserCoupon = dataList.get(i);
            log.info("mtUserCoupon.getUsedTime():"+mtUserCoupon.getUsedTime());
        }*/
        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(dataList, pageRequest, pageHelper.getTotal());
        PaginationResponse<MtUserCoupon> paginationResponse = new PaginationResponse(pageImpl, MtUserCoupon.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(dataList);

        return paginationResponse;
    }

    /**
     * 获取用户卡券列表
     *
     * @param paramMap
     */
    @Override
    @Transactional
    public ResponseObject getUserCouponList(Map<String, Object> paramMap) {

        Integer pageNumber = paramMap.get("pageNumber") == null ? Constants.PAGE_NUMBER : Integer.parseInt(paramMap.get("pageNumber").toString());
        Integer pageSize = paramMap.get("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(paramMap.get("pageSize").toString());
        String userId = paramMap.get("userId") == null ? "" : paramMap.get("userId").toString();
        String status = paramMap.get("status") == null ? "" : paramMap.get("status").toString();
        String type = paramMap.get("type") == null ? "" : paramMap.get("type").toString();
        String mobile = paramMap.get("mobile") == null ? "" : paramMap.get("mobile").toString();
        String storeId = paramMap.get("storeId") == null ? "" : paramMap.get("storeId").toString();
        String couponId = paramMap.get("couponId") == null ? "" : paramMap.get("couponId").toString();
        String code = paramMap.get("code") == null ? "" : paramMap.get("code").toString();
        // 1表示查询 H小时卡;N次数卡 ,2表示查询 C优惠券
        Integer queryTypeScope = paramMap.get("queryTypeScope") == null ? 1 : Integer.parseInt(paramMap.get("queryTypeScope").toString());

        Page<MtUserCoupon> pageHelper = PageHelper.startPage(pageNumber, pageSize);
        LambdaQueryWrapper<MtUserCoupon> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ne(MtUserCoupon::getStatus, "D");

        YxUser user = userService.getById(userId);
        WechatUserDto wechatUserDto = null;
        if(user!=null){
            wechatUserDto = user.getWxProfile();
            log.info("wechatUserDto.toString():" + wechatUserDto.toString());
            log.info("wechatUserDto.getRoutineOpenid():" + wechatUserDto.getRoutineOpenid());
            log.info("wechatUserDto.getNickname():" + wechatUserDto.getNickname());
            log.info(" wechatUserDto.getHeadimgurl():" + wechatUserDto.getHeadimgurl());
            log.info("user.getUid:" + user.getUid());
        }





        // 处理已失效
/*        if (pageNumber <= 1 && StringUtil.isNotEmpty(userId)) {
            List<String> statusList = Arrays.asList(UserCouponStatusEnum.UNUSED.getKey());
            List<MtUserCoupon> data = mtUserCouponMapper.getUserCouponList(Integer.parseInt(userId), statusList);
            for (MtUserCoupon uc : data) {
                MtCoupon coupon = couponService.queryCouponById(uc.getCouponId());
                // 已过期
                if (coupon.getEndTime().before(new Date())) {
                    uc.setStatus(UserCouponStatusEnum.EXPIRE.getKey());
                    uc.setUpdateTime(new Date());
                    mtUserCouponMapper.updateById(uc);
                }
                // 已删除
                if (coupon.getStatus().equals(StatusEnum.DISABLE.getKey())) {
                    uc.setStatus(UserCouponStatusEnum.DISABLE.getKey());
                    uc.setUpdateTime(new Date());
                    mtUserCouponMapper.updateById(uc);
                }
            }
        }*/

        if (StringUtil.isNotEmpty(status)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getStatus, status);
        }
        if (StringUtil.isNotEmpty(userId)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getUserId, userId);
        }
        if (StringUtil.isNotEmpty(mobile)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getMobile, mobile);
        }
        if (queryTypeScope == 1) {

            String types = CouponTypeEnum.HOUR.getKey() + "," + CouponTypeEnum.NUMTIMES.getKey();
            lambdaQueryWrapper.in(MtUserCoupon::getType, Arrays.asList(types.split(",")));

        } else if (queryTypeScope == 2) {

            lambdaQueryWrapper.eq(MtUserCoupon::getType, CouponTypeEnum.COUPON.getKey());

        }
        if (StringUtil.isNotEmpty(storeId)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getStoreId, storeId);
        }
        if (StringUtil.isNotEmpty(couponId)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getCouponId, couponId);
        }
        if (StringUtil.isNotEmpty(code)) {
            lambdaQueryWrapper.eq(MtUserCoupon::getCode, code);
        }

        lambdaQueryWrapper.orderByDesc(MtUserCoupon::getId);
        List<MtUserCoupon> userCouponList = mtUserCouponMapper.selectList(lambdaQueryWrapper);

        List<MyCouponDto> content = new ArrayList<>();
        for (int i = 0; i < userCouponList.size(); i++) {
            MyCouponDto item = new MyCouponDto();
            BeanUtils.copyProperties(userCouponList.get(i), item);
            MtUserCoupon mtUserCoupon = userCouponList.get(i);

            if (item.getType().equals(CouponTypeEnum.COUPON.getKey())) {

                MtCoupon mtCoupon = couponService.queryCouponById(mtUserCoupon.getCouponId());
                BigDecimal outRule = new BigDecimal(0);
                if(!"".equals(mtCoupon.getOutRule())){
                    outRule = BigDecimal.valueOf(Double.valueOf(mtCoupon.getOutRule()));
                }
                //BigDecimal outRule = BigDecimal.valueOf(Double.valueOf(mtCoupon.getOutRule()));
                item.setReachMoney(outRule);

            }

            if (queryTypeScope == 1) {
                if (item.getType().equals(CouponTypeEnum.HOUR.getKey())) {
                    item.setStartText("" + item.getName() + " 剩余 " + item.getRemHourCount() + " 小时数");
                } else if (item.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {
                    item.setStartText("" + item.getName() + " 每次可用 " + item.getRemHourCount() + " 小时,剩余 " + item.getRemUseableCount() + "次数");
                }
            } else {
                item.setStartText(item.getName());
            }
            content.add(item);
        }

/*        if (userCouponList.size() > 0) {
            for (MtUserCoupon userCouponDto : userCouponList) {
                MtCoupon couponInfo = couponService.queryCouponById(userCouponDto.getCouponId());
                //MtUser userInfo = memberService.queryMemberById(userCouponDto.getUserId());
                YxUser userInfo = userService.getById(userCouponDto.getUserId());
                MtStore storeInfo = storeService.queryStoreById(userCouponDto.getStoreId());

                MyCouponDto dto = new MyCouponDto();
                dto.setId(userCouponDto.getId());
                dto.setName(couponInfo.getName());
                dto.setCode(userCouponDto.getCode());
                dto.setCouponId(couponInfo.getId());
                dto.setUseRule(couponInfo.getDescription());

*//*                String image = couponInfo.getImage();
                String baseImage = settingService.getUploadBasePath();
                dto.setImage(baseImage + image);*//*
                dto.setStatus(userCouponDto.getStatus());
                dto.setAmount(userCouponDto.getAmount());
                dto.setBalance(userCouponDto.getBalance());
                dto.setType(couponInfo.getType());
                dto.setUsedTime(userCouponDto.getUsedTime());
                dto.setCreateTime(userCouponDto.getCreateTime());
                dto.setUserInfo(userInfo);
                dto.setStoreInfo(storeInfo);

                boolean canUse = couponService.isCouponEffective(couponInfo);
                if (!userCouponDto.getStatus().equals(UserCouponStatusEnum.UNUSED.getKey())) {
                    canUse = false;
                }
                dto.setCanUse(canUse);


*//*                String effectiveDate = DateUtil.formatDate(couponInfo.getBeginTime(), "yyyy.MM.dd") + "-" + DateUtil.formatDate(couponInfo.getEndTime(), "yyyy.MM.dd");
                dto.setEffectiveDate(effectiveDate);

                String tips = "";

                // 优惠券tips
                if (couponInfo.getType().equals(CouponTypeEnum.COUPON.getKey())) {
                    if (StringUtil.isNotEmpty(couponInfo.getOutRule()) && Integer.parseInt(couponInfo.getOutRule()) > 0) {
                        tips = "满" + couponInfo.getOutRule() + "可用";
                    } else {
                        tips = "无门槛券";
                    }
                }

                // 预存券tips
                if (couponInfo.getType().equals(CouponTypeEnum.PRESTORE.getKey())) {
                    tips = "￥" + userCouponDto .getAmount() + "，余额￥" + userCouponDto.getBalance();
                }

                // 计次卡tips
                if (couponInfo.getType().equals(CouponTypeEnum.TIMER.getKey())) {
                    Long confirmNum = confirmLogService.getConfirmNum(userCouponDto.getId());
                    tips = "已集"+ confirmNum +"次，需集满" + couponInfo.getOutRule() + "次";
                }

                dto.setTips(tips);*//*
                dataList.add(dto);
            }*/
        // }

        PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
        PageImpl pageImpl = new PageImpl(content, pageRequest, pageHelper.getTotal());
        PaginationResponse<MyCouponDto> paginationResponse = new PaginationResponse(pageImpl, MyCouponDto.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(content);

        return new ResponseObject(200, "查询成功", paginationResponse);
    }


    @Override
    public Map<String, Object> queryAll(MtUserCouponQueryCriteria criteria, Pageable pageable) {
        return null;
    }

    @Override
    public List<MtCoupon> queryAll(MtUserCouponQueryCriteria criteria) {
        return null;
    }

    /**
     * 领取卡券(优惠券、计次卡)
     * @param receiveParam
     * @return
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean receiveCoupon(CouponReceiveParam receiveParam){
        Integer couponId = receiveParam.getCouponId() == null ? 0 : receiveParam.getCouponId();
        Integer userId = receiveParam.getUserId() == null ? 0 : receiveParam.getUserId();
        Integer num = receiveParam.getNum() == null ? 1 : receiveParam.getNum();
        String receiveCode = receiveParam.getReceiveCode() == null ? "" : receiveParam.getReceiveCode();
        Integer userCouponId = 0;
        MtCoupon couponInfo = couponService.queryCouponById(couponId);
        if (couponInfo == null) {
            MtUserCoupon userCoupon = mtUserCouponMapper.findByCode(receiveCode);
            if (userCoupon != null) {
                if (userCoupon.getUserId() != null && userCoupon.getUserId() > 0) {
                    if (userCoupon.getUserId().compareTo(userId) == 0) {
                        //throw new BusinessCheckException(Message.HAS_COUPON);
                        throw new XunyinException(Message.HAS_COUPON);
                    } else {
                        //throw new BusinessCheckException(Message.CODE_ERROR);
                        throw new XunyinException(Message.CODE_ERROR);
                    }
                }
                couponInfo = couponService.queryCouponById(userCoupon.getCouponId());
                userCouponId = userCoupon.getId();
            } else {
                //throw new BusinessCheckException(Message.CODE_ERROR_1);
                throw new XunyinException(Message.CODE_ERROR);
            }
            if (couponInfo == null) {
                //throw new BusinessCheckException(Message.COUPON_NOT_EXIST);
                throw new XunyinException(Message.COUPON_NOT_EXIST);
            }
        }

        // 卡券类型检查
        if (couponInfo.getType().equals(CouponTypeEnum.PRESTORE.getKey())) {
            throw new XunyinException(Message.COUPON_TYPE_ERROR);
        }

        //MtCouponGroup groupInfo = couponGroupService.queryCouponGroupById(couponInfo.getGroupId());
        //MtUser userInfo = memberService.queryMemberById(userId);
        YxUser userInfo = yxUserMapper.selectById(userId.longValue());
        if (null == userInfo) {
            throw new XunyinException(Message.USER_NOT_EXIST);
        }

        // 会员等级限制
        if (couponInfo.getGradeIds() != null && StringUtil.isNotEmpty(couponInfo.getGradeIds())) {
            String gradeIds[] = couponInfo.getGradeIds().split(",");
            if (gradeIds.length > 0) {
                boolean isContains = Arrays.asList(gradeIds).contains(userInfo.getGradeId()+"");
                if (!isContains) {
                    throw new XunyinException(Message.GRADE_ERROR);
                }
            }
        }

        // 是否需要领取码
        if (couponInfo.getReceiveCode() != null && StringUtil.isNotEmpty(couponInfo.getReceiveCode())) {
            if (StringUtil.isEmpty(receiveCode)) {
                throw new XunyinException(Message.NEED_CODE);
            }
            // 线下发放的领取码
            if (couponInfo.getSendWay().equals(SendWayEnum.OFFLINE.getKey())) {
                MtUserCoupon userCoupon = mtUserCouponMapper.findByCode(receiveCode);
                if (userCoupon == null || !userCoupon.getCode().equals(receiveCode)) {
                    throw new XunyinException(Message.CODE_ERROR_1);
                } else {
                    userCouponId = userCoupon.getId();
                }
            }
            // 前台领取的领取码
            if (couponInfo.getSendWay().equals(SendWayEnum.FRONT.getKey()) && !receiveCode.equals(couponInfo.getReceiveCode())) {
                throw new XunyinException(Message.CODE_ERROR);
            }
        }

        // 是否已经领取
        List<String> statusList = Arrays.asList(UserCouponStatusEnum.UNUSED.getKey(), UserCouponStatusEnum.USED.getKey(), UserCouponStatusEnum.EXPIRE.getKey());
        List<MtUserCoupon> userCouponData = mtUserCouponMapper.getUserCouponListByCouponId(userId, couponId, statusList);
        if ((userCouponData.size() >= couponInfo.getLimitNum()) && (couponInfo.getLimitNum() > 0)) {
            throw new XunyinException(Message.MAX_COUPON_LIMIT);
        }

        // 积分不足以领取
/*        if (couponInfo.getPoint() != null && couponInfo.getPoint() > 0) {
            if (userInfo.getPoint() < couponInfo.getPoint()) {
                throw new BusinessCheckException(Message.POINT_LIMIT);
            }
        }*/

        // 可领取多张，领取序列号
        StringBuffer uuid = new StringBuffer();
        uuid.append(SeqUtil.getRandomNumber(4));
        uuid.append(SeqUtil.getRandomNumber(4));
        uuid.append(SeqUtil.getRandomNumber(4));
        uuid.append(SeqUtil.getRandomNumber(4));

        for (int i = 1; i <= num; i++) {
            MtUserCoupon userCoupon = new MtUserCoupon();
            if (userCouponId > 0) {
                userCoupon = mtUserCouponMapper.selectById(userCouponId);
            }

            userCoupon.setCouponId(couponInfo.getId());
            userCoupon.setType(couponInfo.getType());
            userCoupon.setAmount(couponInfo.getAmount());
            //userCoupon.setGroupId(groupInfo.getId());
            userCoupon.setMobile(userInfo.getPhone());
            userCoupon.setUserId(userInfo.getUid().intValue());
            userCoupon.setStatus(UserCouponStatusEnum.UNUSED.getKey());
            userCoupon.setCreateTime(new Date());
            userCoupon.setUpdateTime(new Date());
            userCoupon.setExpireTime(couponInfo.getEndTime());
/*            if (couponInfo.getExpireType().equals(CouponExpireTypeEnum.FLEX.getKey())) {
                Date expireTime = new Date();
                Calendar c = Calendar.getInstance();
                c.setTime(expireTime);
                c.add(Calendar.DATE, couponInfo.getExpireTime());
                expireTime = c.getTime();
                userCoupon.setExpireTime(expireTime);
            }*/

            // 12位随机数
            StringBuffer code = new StringBuffer();
            code.append(SeqUtil.getRandomNumber(4));
            code.append(SeqUtil.getRandomNumber(4));
            code.append(SeqUtil.getRandomNumber(4));
            code.append(SeqUtil.getRandomNumber(4));
            userCoupon.setCode(code.toString());
            userCoupon.setUuid(uuid.toString());
            if (userCoupon.getId() != null) {
                mtUserCouponMapper.updateById(userCoupon);
            } else {
                mtUserCouponMapper.insert(userCoupon);
            }
        }

        // 是否需要扣除相应积分
/*        if (couponInfo.getPoint() != null && couponInfo.getPoint() > 0) {
            MtPoint reqPointDto = new MtPoint();
            reqPointDto.setUserId(userId);
            reqPointDto.setAmount(-couponInfo.getPoint());
            reqPointDto.setDescription("领取"+ couponInfo.getName() + "扣除" +couponInfo.getPoint() +"积分");
            reqPointDto.setOperator("");
            pointService.addPoint(reqPointDto);
        }*/

        return true;
    }

    @Override
    public boolean preStore(Map<String, Object> paramMap) {
        return false;
    }

    @Override
    public List<MtUserCoupon> getUserCouponList(Integer userId, List<String> statusList,String refGive) {
        //List<String> statusList = Arrays.asList(UserCouponStatusEnum.UNUSED.getKey(), UserCouponStatusEnum.USED.getKey(), UserCouponStatusEnum.EXPIRE.getKey());
        List<MtUserCoupon> userCouponData = mtUserCouponMapper.getUserCouponList(userId, statusList,refGive);
        return userCouponData;
    }

/*    @Override
    public ResponseObject getUserCouponList(Map<String, Object> paramMap) {
        return null;
    }*/

    @Override
    public List<CouponDto> getPayAbleCouponList(Integer userId, String type) {
        return null;
    }

    @Override
    public List<MtUserCoupon> getUserCouponDetail(Integer userId, Integer couponId) {
        return null;
    }

    @Override
    public MtUserCoupon getUserCouponDetail(Integer userCouponId) {
        return null;
    }

    @Override
    public List<MtUserCoupon> getUserCouponListByExpireTime(Integer userId, String status, String startTime, String endTime) {
        return null;
    }


    /**
     * 发放卡券、优惠券
     *
     * @param orderId
     * @param couponId
     * @param userId
     * @return
     */
    @Override
    public boolean buyCouponItem(String orderId, Integer couponId, Integer userId, Integer storeId,String refGive) {
        YxUser userInfo = userService.getById(userId.longValue());
        if (userInfo == null) {
            throw new XunyinException(Message.COUPON_NOT_EXIST);
            //throw new BusinessCheckException(Message.USER_NOT_EXIST);
        }

        MtCoupon couponInfo = couponService.queryCouponById(couponId);
        MtUserCoupon userCoupon = new MtUserCoupon();
        userCoupon.setCouponId(couponId);
        userCoupon.setType(couponInfo.getType());
        // 购买小时卡券
        if (couponInfo.getType().equals(CouponTypeEnum.HOUR.getKey())) {
            userCoupon.setHourCount(couponInfo.getHourCount());
            userCoupon.setRemHourCount(BigDecimal.valueOf(couponInfo.getHourCount()));
        }
        // 购买次卡券
        if (couponInfo.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {
            userCoupon.setEveryUseableHourCount(couponInfo.getEveryUseableHourCount());
            userCoupon.setUseableCount(couponInfo.getUseableCount());
            userCoupon.setRemUseableCount(couponInfo.getUseableCount());
        }

        userCoupon.setName(couponInfo.getName());
        userCoupon.setStoreId(storeId);
        userCoupon.setGroupId(couponInfo.getGroupId());
        userCoupon.setMobile(userInfo.getPhone());
        userCoupon.setUserId(userInfo.getUid().intValue());
        userCoupon.setStatus(UserCouponStatusEnum.UNUSED.getKey());
        userCoupon.setRefGive(refGive);
        userCoupon.setCreateTime(new Date());
        userCoupon.setUpdateTime(new Date());
        // 判断卡券是否有过期时间 0表示没有，1表示有
        // 有效期-天数 0 表示不限制，大于0表示具体限制天数
        if (couponInfo.getLimitDay() > 0) {
            userCoupon.setIsExpire(1);
            userCoupon.setExpireTime(DateUtil.addDate(new Date(), Calendar.DATE, couponInfo.getLimitDay()));
        } else {
            userCoupon.setIsExpire(0);
        }
        userCoupon.setOrderId(orderId);
        userCoupon.setAmount(couponInfo.getAmount());
        userCoupon.setBalance(couponInfo.getAmount());

        userCoupon.setExpireTime(couponInfo.getEndTime());

        // 12位随机数
        StringBuffer code = new StringBuffer();
        code.append(SeqUtil.getRandomNumber(4));
        code.append(SeqUtil.getRandomNumber(4));
        code.append(SeqUtil.getRandomNumber(4));
        code.append(SeqUtil.getRandomNumber(4));
        userCoupon.setCode(code.toString());
        userCoupon.setUuid(code.toString());

        mtUserCouponMapper.insert(userCoupon);
        return true;
    }

    /**
     * 用户卡券(小时卡、次数卡)购买
     *
     * @param paramMap
     */
    public boolean userBuyConpon(Map<String, Object> paramMap) {
        Integer couponId = paramMap.get("couponId") == null ? 0 : Integer.parseInt(paramMap.get("couponId").toString());
        Integer userId = paramMap.get("userId") == null ? 0 : Integer.parseInt(paramMap.get("userId").toString());
        String orderId = paramMap.get("orderId") == null ? "0" : paramMap.get("orderId").toString();
        Integer storeId = paramMap.get("storeId") == null ? 0 : Integer.parseInt(paramMap.get("storeId").toString());
        String refGive = paramMap.get("refGive") == null ? "D" : paramMap.get("refGive").toString();

        if (couponId <= 0 || userId <= 0) {
            throw new XunyinException(Message.PARAM_ERROR);
            // throw new BusinessCheckException(Message.PARAM_ERROR);
        }

        MtCoupon couponInfo = couponService.queryCouponById(couponId);
        if (couponInfo == null) {
            throw new XunyinException(Message.COUPON_NOT_EXIST);
            //throw new BusinessCheckException(Message.COUPON_NOT_EXIST);
        }
        //YxUserQueryVo userInfo = userService.getYxUserById(userId.longValue());
        YxUser userInfo = userService.getById(userId.longValue());
        if (userInfo == null) {
            throw new XunyinException(Message.COUPON_NOT_EXIST);
            //throw new BusinessCheckException(Message.USER_NOT_EXIST);
        }

        MtUserCoupon userCoupon = new MtUserCoupon();
        userCoupon.setCouponId(couponInfo.getId());
        userCoupon.setType(couponInfo.getType());
        // 购买小时卡券
        if (couponInfo.getType().equals(CouponTypeEnum.HOUR.getKey())) {
            userCoupon.setHourCount(couponInfo.getHourCount());
            userCoupon.setRemHourCount(BigDecimal.valueOf(couponInfo.getHourCount()));
        }
        // 购买次卡券
        if (couponInfo.getType().equals(CouponTypeEnum.NUMTIMES.getKey())) {
            userCoupon.setEveryUseableHourCount(couponInfo.getEveryUseableHourCount());
            userCoupon.setUseableCount(couponInfo.getUseableCount());
            userCoupon.setRemUseableCount(couponInfo.getUseableCount());
        }

        userCoupon.setName(couponInfo.getName());
        userCoupon.setStoreId(storeId);
        userCoupon.setGroupId(couponInfo.getGroupId());
        userCoupon.setMobile(userInfo.getPhone());
        userCoupon.setUserId(userInfo.getUid().intValue());
        userCoupon.setStatus(UserCouponStatusEnum.UNUSED.getKey());
        userCoupon.setRefGive(refGive);
        userCoupon.setCreateTime(new Date());
        userCoupon.setUpdateTime(new Date());
        // 判断卡券是否有过期时间 0表示没有，1表示有
        // 有效期-天数 0 表示不限制，大于0表示具体限制天数
        if (couponInfo.getLimitDay() > 0) {
            userCoupon.setIsExpire(1);
            userCoupon.setExpireTime(DateUtil.addDate(new Date(), Calendar.DATE, couponInfo.getLimitDay()));
        } else {
            userCoupon.setIsExpire(0);
        }
        userCoupon.setOrderId(orderId);
        userCoupon.setAmount(couponInfo.getAmount());
        userCoupon.setBalance(couponInfo.getAmount());

        // 12位随机数
        StringBuffer code = new StringBuffer();
        code.append(SeqUtil.getRandomNumber(4));
        code.append(SeqUtil.getRandomNumber(4));
        code.append(SeqUtil.getRandomNumber(4));
        code.append(SeqUtil.getRandomNumber(4));
        userCoupon.setCode(code.toString());
        userCoupon.setUuid(code.toString());

        mtUserCouponMapper.insert(userCoupon);
        return true;
    }

    /**
     * 更改用户卡券状态
     *
     * @param userCouponId
     */
    @Override
    public Integer updateStatus(Integer userCouponId, String status) {
        MtUserCoupon userCoupon = mtUserCouponMapper.selectById(userCouponId);
        if (userCoupon != null) {
            userCoupon.setStatus(status);
            userCoupon.setUpdateTime(new Date());
            mtUserCouponMapper.updateById(userCoupon);

        } else {
            return 0;
        }
        return userCouponId;
    }

    /**
     * 获取订单统计数据
     * @return OrderStatDto
     */
    @Override
    public ConponStatDto getUserConponStat(Integer storeId, String storeIds, String type,String status,String mobile) {

        ConponStatDto conponStatDto = new ConponStatDto();

//        if (storeId == 0) {
//            storeId = null;
//        }

        if("".equals(type)){
            type = null;
        }

        if("".equals(status)){
            status = null;
        }

        if("".equals(mobile)){
            mobile = null;
        }

        log.info("getUserConponStat-storeIds:"+storeIds);
        log.info("getUserConponStat-type:"+type);

        log.info("getUserConponStat-status:"+status);

        log.info("getUserConponStat-mobile:"+mobile);

        conponStatDto.setSumUserCouponMoney(mtUserCouponMapper.sumUserCouponMoney(storeId,storeIds,type,status,mobile));

        return conponStatDto;

    }


}
